// 资源类型定义
const RESOURCE_TYPES = {
    // 基础资源
    GOLD: {
        id: 'gold',
        name: '金币',
        icon: '🪙',
        description: '基础货币，可用于投资和交易',
        baseValue: 1.0,
        color: '#FFD700'
    },
    TRUST: {
        id: 'trust',
        name: '信任值',
        icon: '🤝',
        description: '影响AI返还率和特殊机会',
        baseValue: 2.0,
        color: '#4CAF50'
    },
    RISK: {
        id: 'risk',
        name: '风险点',
        icon: '⚠️',
        description: '增加投资风险和回报',
        baseValue: 1.5,
        color: '#FF5722'
    }
};

// 资源池配置
const POOL_CONFIGS = {
    // 基础游戏资源池
    BASIC: {
        name: '基础资源池',
        initialResources: {
            [RESOURCE_TYPES.GOLD.id]: 10
        }
    },
    // 标准游戏资源池
    STANDARD: {
        name: '标准资源池',
        initialResources: {
            [RESOURCE_TYPES.GOLD.id]: 8,
            [RESOURCE_TYPES.TRUST.id]: 2
        }
    },
    // 高级游戏资源池
    ADVANCED: {
        name: '高级资源池',
        initialResources: {
            [RESOURCE_TYPES.GOLD.id]: 6,
            [RESOURCE_TYPES.TRUST.id]: 3,
            [RESOURCE_TYPES.RISK.id]: 1
        }
    }
};

// 游戏状态
let gameState = {
    // 玩家资源
    playerResources: {
        [RESOURCE_TYPES.GOLD.id]: 10,
        [RESOURCE_TYPES.TRUST.id]: 0,
        [RESOURCE_TYPES.RISK.id]: 0
    },
    // AI资源
    aiResources: {
        [RESOURCE_TYPES.GOLD.id]: 0,
        [RESOURCE_TYPES.TRUST.id]: 0,
        [RESOURCE_TYPES.RISK.id]: 0
    },
    currentPhase: 'investment', // investment, return, result
    investment: {
        [RESOURCE_TYPES.GOLD.id]: 0,
        [RESOURCE_TYPES.TRUST.id]: 0,
        [RESOURCE_TYPES.RISK.id]: 0
    },
    multipliedAmount: 0,
    returnAmount: 0,
    currentRound: 1,
    maxRounds: 5,
    poolConfig: POOL_CONFIGS.BASIC, // 当前使用的资源池配置
    history: []
};

// AI策略函数
const aiStrategies = {
    // 好人AI - 返还50%
    good: (amount) => Math.round(amount * 0.5),

    // 坏人AI - 返还0%
    bad: (amount) => 0,

    // 公平AI - 返还33%（让你刚好回本）
    fair: (amount) => Math.round(amount * 0.33),
    
    // 心理战AI - 根据历史投资额动态调整返还比例
    psychological: (amount, history) => {
        // 如果是第一轮，返还40%作为基准
        if (!history || history.length === 0) {
            return Math.round(amount * 0.4);
        }
        
        // 获取上一轮的投资记录
        const lastRound = history[history.length - 1];
        const lastInvestment = lastRound.investment;
        
        // 心理战策略：
        // 1. 如果玩家上一轮投资增加，AI会返还更多以鼓励继续增加投资
        // 2. 如果玩家上一轮投资减少，AI会少返还以"惩罚"不信任行为
        // 3. 偶尔会有"欺骗"行为，突然少返还以测试玩家反应
        
        // 获取前一轮的投资记录（如果有）
        const prevRound = history.length > 1 ? history[history.length - 2] : null;
        const prevInvestment = prevRound ? prevRound.investment : 5; // 假设基准投资为5
        
        // 计算投资变化
        const investmentChange = lastInvestment - prevInvestment;
        
        // 基础返还率40%
        let returnRate = 0.4;
        
        // 根据投资变化调整返还率
        if (investmentChange > 0) {
            // 投资增加，提高返还率
            returnRate += 0.1;
        } else if (investmentChange < 0) {
            // 投资减少，降低返还率
            returnRate -= 0.15;
        }
        
        // 随机欺骗行为（10%概率）
        const deception = Math.random() < 0.1;
        if (deception) {
            returnRate = 0.1; // 突然大幅降低返还率
        }
        
        // 确保返还率在合理范围内
        returnRate = Math.max(0.05, Math.min(0.8, returnRate));
        
        return Math.round(amount * returnRate);
    },
    
    // 报复性AI - 记住玩家行为，对低投资进行惩罚
    vengeful: (amount, history) => {
        // 如果是第一轮，返还40%作为基准
        if (!history || history.length === 0) {
            return Math.round(amount * 0.4);
        }
        
        // 计算玩家的平均投资比例（相对于初始10金币）
        const avgInvestmentRatio = history.reduce((sum, record) => sum + record.investment / 10, 0) / history.length;
        
        // 根据平均投资比例决定返还率
        // 投资比例高 = 高返还率，投资比例低 = 低返还率
        const returnRate = avgInvestmentRatio * 0.8; // 最高返还率80%
        
        return Math.round(amount * returnRate);
    }
};

// DOM元素统一收口
const elements = {
    // 统计信息
    playerCoins: document.getElementById('playerCoins'),
    aiCoins: document.getElementById('aiCoins'),
    playerResourcesContainer: document.getElementById('playerResourcesContainer'),
    aiResourcesContainer: document.getElementById('aiResourcesContainer'),

    // 阶段容器
    investmentPhase: document.getElementById('investmentPhase'),
    returnPhase: document.getElementById('returnPhase'),
    resultPhase: document.getElementById('resultPhase'),

    // 投资阶段元素
    investmentSlider: document.getElementById('investmentSlider'),
    investmentValue: document.getElementById('investmentValue'),
    trustInvestmentGroup: document.getElementById('trustInvestmentGroup'),
    trustInvestmentSlider: document.getElementById('trustInvestmentSlider'),
    trustInvestmentValue: document.getElementById('trustInvestmentValue'),
    riskInvestmentGroup: document.getElementById('riskInvestmentGroup'),
    riskInvestmentSlider: document.getElementById('riskInvestmentSlider'),
    riskInvestmentValue: document.getElementById('riskInvestmentValue'),
    trustBonusPreview: document.getElementById('trustBonusPreview'),
    riskPreview: document.getElementById('riskPreview'),
    confirmInvestment: document.getElementById('confirmInvestment'),

    // 返还阶段元素
    investedAmount: document.getElementById('investedAmount'),
    multipliedAmount: document.getElementById('multipliedAmount'),
    returnAmount: document.getElementById('returnAmount'),
    investmentDetails: document.getElementById('investmentDetails'),
    multipliedDetails: document.getElementById('multipliedDetails'),
    returnDetails: document.getElementById('returnDetails'),
    multiplierDisplay: document.getElementById('multiplierDisplay'),
    baseMultiplierDisplay: document.getElementById('baseMultiplierDisplay'),
    trustBonusDisplay: document.getElementById('trustBonusDisplay'),
    riskModifierDisplay: document.getElementById('riskModifierDisplay'),
    returnRateDisplay: document.getElementById('returnRateDisplay'),

    // 结果阶段元素
    playerFinal: document.getElementById('playerFinal'),
    aiFinal: document.getElementById('aiFinal'),
    playerResultResources: document.getElementById('playerResultResources'),
    aiResultResources: document.getElementById('aiResultResources'),
    restartGame: document.getElementById('restartGame'),
    currentRound: document.getElementById('currentRound'),
    totalRounds: document.getElementById('totalRounds'),

    // 资源池选择
    poolSelector: document.getElementById('poolSelector'),

    // AI策略选择
    strategySelect: document.getElementById('strategySelect')
};

// 工具函数：安全绑定事件
function addListenerIfPresent(target, event, handler) {
    if (target && typeof target.addEventListener === 'function') {
        target.addEventListener(event, handler);
    }
}

/**
 * 初始化资源滑块
 * @param {HTMLElement} slider 滑块元素
 * @param {HTMLElement} valueDisplay 值显示元素
 * @param {number} maxValue 最大值
 * @param {number} initialValue 初始值
 */
function initResourceSlider(slider, valueDisplay, maxValue, initialValue = 0) {
    if (!slider) return;
    
    // 设置滑块范围和初始值
    slider.min = 0;
    slider.max = maxValue;
    slider.value = Math.min(initialValue, maxValue);
    
    // 更新显示值
    if (valueDisplay) {
        valueDisplay.textContent = slider.value;
    }
    
    // 添加事件监听
    slider.addEventListener('input', function() {
        if (valueDisplay) {
            valueDisplay.textContent = this.value;
        }
        
        // 添加滑块动画效果
        const value = parseInt(this.value);
        const max = parseInt(this.max);
        const percentage = (value / max) * 100;
        this.style.background = `linear-gradient(to right, #3498db ${percentage}%, #ddd ${percentage}%)`;
        
        // 更新投资预览
        updateInvestmentPreview();
    });
    
    // 初始化滑块背景
    const value = parseInt(slider.value);
    const max = parseInt(slider.max);
    const percentage = (value / max) * 100;
    slider.style.background = `linear-gradient(to right, #3498db ${percentage}%, #ddd ${percentage}%)`;
}

/**
 * 更新投资预览
 * 根据当前选择的投资值更新预览信息
 */
function updateInvestmentPreview() {
    const trustValue = elements.trustInvestmentSlider ? parseInt(elements.trustInvestmentSlider.value) || 0 : 0;
    const riskValue = elements.riskInvestmentSlider ? parseInt(elements.riskInvestmentSlider.value) || 0 : 0;
    
    // 更新信任值加成预览
    if (elements.trustBonusPreview && trustValue > 0) {
        const trustBonus = trustValue * 0.05;
        elements.trustBonusPreview.style.display = 'block';
        elements.trustBonusPreview.querySelector('strong').textContent = `+${trustBonus.toFixed(1)}x`;
    } else if (elements.trustBonusPreview) {
        elements.trustBonusPreview.style.display = 'none';
    }
    
    // 更新风险点预览
    if (elements.riskPreview && riskValue > 0) {
        elements.riskPreview.style.display = 'block';
    } else if (elements.riskPreview) {
        elements.riskPreview.style.display = 'none';
    }
}

/**
 * 根据资源池配置更新UI
 * @param {Object} poolConfig 资源池配置
 */
function updateUIForPoolConfig(poolConfig) {
    // 获取玩家资源
    const playerResources = gameState.playerResources;
    
    // 更新金币滑块
    initResourceSlider(
        elements.investmentSlider, 
        elements.investmentValue, 
        playerResources[RESOURCE_TYPES.GOLD.id] || 0, 
        Math.min(5, playerResources[RESOURCE_TYPES.GOLD.id] || 0)
    );
    
    // 更新信任值滑块和显示
    if (elements.trustInvestmentGroup && elements.trustInvestmentSlider) {
        const trustAmount = playerResources[RESOURCE_TYPES.TRUST.id] || 0;
        if (trustAmount > 0) {
            elements.trustInvestmentGroup.style.display = 'block';
            initResourceSlider(elements.trustInvestmentSlider, elements.trustInvestmentValue, trustAmount, 0);
        } else {
            elements.trustInvestmentGroup.style.display = 'none';
        }
    }
    
    // 更新风险点滑块和显示
    if (elements.riskInvestmentGroup && elements.riskInvestmentSlider) {
        const riskAmount = playerResources[RESOURCE_TYPES.RISK.id] || 0;
        if (riskAmount > 0) {
            elements.riskInvestmentGroup.style.display = 'block';
            initResourceSlider(elements.riskInvestmentSlider, elements.riskInvestmentValue, riskAmount, 0);
        } else {
            elements.riskInvestmentGroup.style.display = 'none';
        }
    }
    
    // 更新投资预览
    updateInvestmentPreview();
}

/**
 * 调整资源池配置
 * 根据玩家数量动态调整资源池
 * @param {number} playerCount 玩家数量
 */
function adjustPoolForPlayerCount(playerCount = 1) {
    // 获取当前资源池配置
    const currentPool = gameState.poolConfig;
    
    // 基础调整：每多一个玩家，基础资源增加50%
    const multiplier = 1 + (playerCount - 1) * 0.5;
    
    // 创建新的资源池配置
    const adjustedPool = {
        name: currentPool.name,
        initialResources: {}
    };
    
    // 调整每种资源
    for (const resourceId in currentPool.initialResources) {
        const baseAmount = currentPool.initialResources[resourceId];
        adjustedPool.initialResources[resourceId] = Math.round(baseAmount * multiplier);
    }
    
    // 更新游戏状态
    gameState.poolConfig = adjustedPool;
    
    // 重置游戏
    resetGame();
}

// 初始化游戏
function initGame() {
    // 初始化资源池选择器
    if (elements.poolSelector) {
        addListenerIfPresent(elements.poolSelector, 'change', function() {
            const selectedPoolName = this.value;
            const selectedPool = Object.values(POOL_CONFIGS).find(pool => pool.name === selectedPoolName) || POOL_CONFIGS.BASIC;
            gameState.poolConfig = selectedPool;
            resetGame();
        });
    }
    
    // 确认投资按钮（存在性校验）
    if (elements.confirmInvestment) {
        addListenerIfPresent(elements.confirmInvestment, 'click', function(e) {
            // 添加点击波纹效果
            const button = this;
            const ripple = document.createElement('span');
            ripple.classList.add('ripple-effect');

            const rect = button.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);

            ripple.style.width = ripple.style.height = `${size}px`;
            ripple.style.left = `${e.clientX - rect.left - size/2}px`;
            ripple.style.top = `${e.clientY - rect.top - size/2}px`;

            button.appendChild(ripple);

            setTimeout(() => {
                ripple.remove();
                handleInvestment();
            }, 300);
        });
    }

    // 重新开始按钮（存在性校验 - 某些视图中可能不存在）
    addListenerIfPresent(elements.restartGame, 'click', resetGame);

    // 初始化回合显示
    if (elements.currentRound) {
        elements.currentRound.textContent = gameState.currentRound;
    }
    if (elements.totalRounds) {
        elements.totalRounds.textContent = gameState.maxRounds;
    }
    
    // 根据当前资源池配置更新UI
    updateUIForPoolConfig(gameState.poolConfig);

    // 更新UI显示
    updateUI();

    // 添加页面进入动画
    document.body.classList.add('loaded');
}

/**
 * 计算资源增值
 * 根据不同资源类型和投资组合计算增值
 * @param {Object} investment 投资的资源
 * @returns {Object} 增值后的资源
 */
function calculateMultiplier(investment) {
    // 基础增值倍率
    const baseMultiplier = 3;
    
    // 信任值增益：每点信任值增加5%增值率
    const trustBonus = (investment[RESOURCE_TYPES.TRUST.id] || 0) * 0.05;
    
    // 风险点增益：每点风险点有50%几率增加20%增值率，50%几率减少10%增值率
    let riskModifier = 0;
    const riskPoints = investment[RESOURCE_TYPES.RISK.id] || 0;
    for (let i = 0; i < riskPoints; i++) {
        if (Math.random() < 0.5) {
            riskModifier += 0.2; // 增益
        } else {
            riskModifier -= 0.1; // 损失
        }
    }
    
    // 计算最终倍率，最低为1倍（保底不亏本）
    const finalMultiplier = Math.max(1, baseMultiplier + trustBonus + riskModifier);
    
    // 应用倍率到每种资源
    const multipliedResources = {};
    for (const resourceId in investment) {
        if (investment[resourceId] > 0) {
            multipliedResources[resourceId] = Math.round(investment[resourceId] * finalMultiplier);
        }
    }
    
    return {
        resources: multipliedResources,
        multiplier: finalMultiplier,
        baseMultiplier,
        trustBonus,
        riskModifier
    };
}

// 处理投资
function handleInvestment() {
    // 获取金币投资额
    const goldInvestment = parseInt(elements.investmentSlider.value);
    
    // 获取信任值投资额（如果UI中有该元素）
    let trustInvestment = 0;
    if (elements.trustInvestmentSlider) {
        trustInvestment = parseInt(elements.trustInvestmentSlider.value || 0);
    }
    
    // 获取风险点投资额（如果UI中有该元素）
    let riskInvestment = 0;
    if (elements.riskInvestmentSlider) {
        riskInvestment = parseInt(elements.riskInvestmentSlider.value || 0);
    }
    
    const selectedStrategy = elements.strategySelect.value;

    // 更新游戏状态中的投资
    gameState.investment = {
        [RESOURCE_TYPES.GOLD.id]: goldInvestment,
        [RESOURCE_TYPES.TRUST.id]: trustInvestment,
        [RESOURCE_TYPES.RISK.id]: riskInvestment
    };
    
    // 从玩家资源中扣除投资额
    for (const resourceId in gameState.investment) {
        gameState.playerResources[resourceId] -= gameState.investment[resourceId] || 0;
    }
    
    // 计算增值
    const multiplierResult = calculateMultiplier(gameState.investment);
    gameState.multipliedAmount = multiplierResult.resources;
    
    // 计算总增值金额（用于AI决策）
    const totalMultipliedAmount = Object.values(gameState.multipliedAmount).reduce((sum, val) => sum + val, 0);
    
    // AI决策 - 对于心理战和报复性AI，传入历史记录
    let returnAmount = 0;
    if (selectedStrategy === 'psychological' || selectedStrategy === 'vengeful') {
        returnAmount = aiStrategies[selectedStrategy](totalMultipliedAmount, gameState.history);
    } else {
        returnAmount = aiStrategies[selectedStrategy](totalMultipliedAmount);
    }
    
    // 计算返还的资源分配（按照增值后的比例分配）
    gameState.returnAmount = {};
    const totalMultiplied = Object.values(gameState.multipliedAmount).reduce((sum, val) => sum + val, 0);
    
    if (totalMultiplied > 0) {
        for (const resourceId in gameState.multipliedAmount) {
            const resourceRatio = gameState.multipliedAmount[resourceId] / totalMultiplied;
            gameState.returnAmount[resourceId] = Math.round(returnAmount * resourceRatio);
        }
    }
    
    // 计算当前回合收益
    const playerRoundGain = {};
    const aiRoundGain = {};
    
    for (const resourceId in gameState.multipliedAmount) {
        // 玩家收益 = 返还 - 投资
        playerRoundGain[resourceId] = (gameState.returnAmount[resourceId] || 0) - (gameState.investment[resourceId] || 0);
        
        // AI收益 = 增值 - 返还
        aiRoundGain[resourceId] = (gameState.multipliedAmount[resourceId] || 0) - (gameState.returnAmount[resourceId] || 0);
        
        // 更新玩家和AI的资源
        gameState.playerResources[resourceId] = (gameState.playerResources[resourceId] || 0) + (gameState.returnAmount[resourceId] || 0);
        gameState.aiResources[resourceId] = (gameState.aiResources[resourceId] || 0) + aiRoundGain[resourceId];
    }
    
    // 计算总收益（用于显示和历史记录）
    const totalPlayerGain = Object.values(playerRoundGain).reduce((sum, val) => sum + val, 0);
    const totalAiGain = Object.values(aiRoundGain).reduce((sum, val) => sum + val, 0);
    
    // 立即更新顶部展示
    updateUI();

    // 记录历史
    gameState.history.push({
        round: gameState.currentRound,
        investment: gameState.investment,
        multipliedAmount: gameState.multipliedAmount,
        returnAmount: gameState.returnAmount,
        playerGain: playerRoundGain,
        aiGain: aiRoundGain,
        totalPlayerGain,
        totalAiGain,
        multiplier: multiplierResult.multiplier,
        trustBonus: multiplierResult.trustBonus,
        riskModifier: multiplierResult.riskModifier,
        strategy: selectedStrategy,
        returnRate: totalMultiplied > 0 ? (returnAmount / totalMultiplied).toFixed(2) : 0
    });

    // 同步到本地存储（累积历史）
    try {
        const stored = JSON.parse(localStorage.getItem('trust_fall_history') || '[]');
        stored.push(gameState.history[gameState.history.length - 1]);
        localStorage.setItem('trust_fall_history', JSON.stringify(stored));
    } catch (e) {
        // 忽略本地存储异常，保证游戏不中断
    }

    // 切换到返还阶段
    switchPhase('return');

    // 2秒后显示结果
    setTimeout(() => {
        if (gameState.currentRound < gameState.maxRounds) {
            switchPhase('result');
        } else {
            switchPhase('finalResult');
        }
    }, 2000);
}

// 切换游戏阶段
function switchPhase(phase) {
    // 隐藏所有阶段
    elements.investmentPhase.classList.remove('active');
    elements.returnPhase.classList.remove('active');
    elements.resultPhase.classList.remove('active');
    elements.finalResultPhase && elements.finalResultPhase.classList.remove('active');
    elements.historyPhase && elements.historyPhase.classList.remove('active');

    // 显示当前阶段
    switch(phase) {
        case 'investment':
            elements.investmentPhase.classList.add('active');
            break;
        case 'return':
            elements.returnPhase.classList.add('active');
            updateReturnPhase();
            break;
        case 'result':
            elements.resultPhase.classList.add('active');
            updateResultPhase();
            // 准备下一回合
            gameState.currentRound++;
            setTimeout(() => {
                switchPhase('investment');
            }, 3000);
            break;
        case 'finalResult':
            if (!elements.finalResultPhase) {
                createFinalResultPhase();
            }
            elements.finalResultPhase.classList.add('active');
            updateFinalResultPhase();
            break;
        case 'history':
            if (!elements.historyPhase) {
                createHistoryPhase();
            }
            elements.historyPhase.classList.add('active');
            updateHistoryPhase();
            break;
    }

    gameState.currentPhase = phase;
}

/**
 * 更新资源详情显示
 * @param {HTMLElement} container 容器元素
 * @param {Object} resources 资源对象
 */
function updateResourceDetails(container, resources) {
    if (!container) return;
    
    // 清空现有内容
    container.innerHTML = '';
    
    // 为每种资源创建显示元素
    for (const resourceId in resources) {
        if (resources[resourceId] > 0) {
            const resourceType = Object.values(RESOURCE_TYPES).find(type => type.id === resourceId);
            if (!resourceType) continue;
            
            const resourceElement = document.createElement('div');
            resourceElement.className = 'resource-item';
            resourceElement.innerHTML = `
                <span class="resource-icon" style="color: ${resourceType.color}">${resourceType.icon}</span>
                <span class="resource-amount" id="${container.id}_${resourceId}">0</span>
                <span class="resource-name">${resourceType.name}</span>
            `;
            container.appendChild(resourceElement);
        }
    }
}

// 更新返还阶段显示
function updateReturnPhase() {
    // 更新投资详情
    updateResourceDetails(elements.investmentDetails, gameState.investment);
    
    // 更新增值详情
    updateResourceDetails(elements.multipliedDetails, gameState.multipliedAmount);
    
    // 更新返还详情
    updateResourceDetails(elements.returnDetails, gameState.returnAmount);
    
    // 更新倍率显示
    if (elements.multiplierDisplay) {
        const multiplier = gameState.history[gameState.history.length - 1].multiplier;
        elements.multiplierDisplay.textContent = `${multiplier.toFixed(1)}x`;
    }
    
    // 更新倍率详情
    if (elements.baseMultiplierDisplay) {
        elements.baseMultiplierDisplay.textContent = '3.0x';
    }
    
    // 更新信任值加成显示
    if (elements.trustBonusDisplay) {
        const trustBonus = gameState.history[gameState.history.length - 1].trustBonus;
        if (trustBonus > 0) {
            elements.trustBonusDisplay.style.display = 'block';
            elements.trustBonusDisplay.querySelector('span').textContent = `+${trustBonus.toFixed(1)}x`;
        } else {
            elements.trustBonusDisplay.style.display = 'none';
        }
    }
    
    // 更新风险修正显示
    if (elements.riskModifierDisplay) {
        const riskModifier = gameState.history[gameState.history.length - 1].riskModifier;
        if (riskModifier !== 0) {
            elements.riskModifierDisplay.style.display = 'block';
            const sign = riskModifier > 0 ? '+' : '';
            elements.riskModifierDisplay.querySelector('span').textContent = `${sign}${riskModifier.toFixed(1)}x`;
        } else {
            elements.riskModifierDisplay.style.display = 'none';
        }
    }
    
    // 更新返还率显示
    if (elements.returnRateDisplay) {
        const returnRate = gameState.history[gameState.history.length - 1].returnRate;
        elements.returnRateDisplay.textContent = `${Math.round(parseFloat(returnRate) * 100)}%`;
    }
    
    // 投资金额动画（兼容旧版UI）
    if (elements.investedAmount) {
        elements.investedAmount.textContent = "0";
        const goldInvestment = gameState.investment[RESOURCE_TYPES.GOLD.id] || 0;
        animateNumber(elements.investedAmount, 0, goldInvestment, 500);
    }
    
    // 延迟显示增值金额（兼容旧版UI）
    setTimeout(() => {
        if (elements.multipliedAmount) {
            elements.multipliedAmount.textContent = "0";
            const goldMultiplied = gameState.multipliedAmount[RESOURCE_TYPES.GOLD.id] || 0;
            animateNumber(elements.multipliedAmount, 0, goldMultiplied, 800);
        }
        
        // 再延迟显示返还金额（兼容旧版UI）
        setTimeout(() => {
            if (elements.returnAmount) {
                elements.returnAmount.textContent = "0";
                const goldReturn = gameState.returnAmount[RESOURCE_TYPES.GOLD.id] || 0;
                animateNumber(elements.returnAmount, 0, goldReturn, 1000);
            }
        }, 800);
    }, 600);
    
    // 为新版UI中的每个资源执行动画
    setTimeout(() => {
        // 投资动画
        for (const resourceId in gameState.investment) {
            const element = document.getElementById(`${elements.investmentDetails.id}_${resourceId}`);
            if (element) {
                animateNumber(element, 0, gameState.investment[resourceId], 500);
            }
        }
        
        // 延迟显示增值动画
        setTimeout(() => {
            for (const resourceId in gameState.multipliedAmount) {
                const element = document.getElementById(`${elements.multipliedDetails.id}_${resourceId}`);
                if (element) {
                    animateNumber(element, 0, gameState.multipliedAmount[resourceId], 800);
                }
            }
            
            // 再延迟显示返还动画
            setTimeout(() => {
                for (const resourceId in gameState.returnAmount) {
                    const element = document.getElementById(`${elements.returnDetails.id}_${resourceId}`);
                    if (element) {
                        animateNumber(element, 0, gameState.returnAmount[resourceId], 1000);
                    }
                }
            }, 800);
        }, 600);
    }, 100);
}

// 数字动画效果
function animateNumber(element, start, end, duration) {
    const startTime = performance.now();
    const updateNumber = (currentTime) => {
        const elapsedTime = currentTime - startTime;
        const progress = Math.min(elapsedTime / duration, 1);
        const currentValue = Math.floor(start + progress * (end - start));
        
        element.textContent = currentValue;
        
        if (progress < 1) {
            requestAnimationFrame(updateNumber);
        }
    };
    
    requestAnimationFrame(updateNumber);
}

// 更新结果阶段显示
function updateResultPhase() {
    // 更新玩家资源显示
    updateResourceDetails(elements.playerResultResources, gameState.playerResources);
    
    // 更新AI资源显示
    updateResourceDetails(elements.aiResultResources, gameState.aiResources);
    
    // 使用动画效果显示金币数量（兼容旧版UI）
    if (elements.playerFinal) {
        animateNumber(elements.playerFinal, 0, gameState.playerResources[RESOURCE_TYPES.GOLD.id] || 0, 800);
    }
    if (elements.aiFinal) {
        animateNumber(elements.aiFinal, 0, gameState.aiResources[RESOURCE_TYPES.GOLD.id] || 0, 800);
    }
    
    // 为新版UI中的每个资源执行动画
    setTimeout(() => {
        // 玩家资源动画
        for (const resourceId in gameState.playerResources) {
            const element = document.getElementById(`${elements.playerResultResources.id}_${resourceId}`);
            if (element) {
                animateNumber(element, 0, gameState.playerResources[resourceId], 800);
            }
        }
        
        // AI资源动画
        for (const resourceId in gameState.aiResources) {
            const element = document.getElementById(`${elements.aiResultResources.id}_${resourceId}`);
            if (element) {
                animateNumber(element, 0, gameState.aiResources[resourceId], 800);
            }
        }
    }, 100);
    
    // 显示当前回合信息
    if (elements.currentRound) {
        elements.currentRound.textContent = gameState.currentRound;
        elements.totalRounds.textContent = gameState.maxRounds;
    }
    
    // 添加渐变背景色效果，根据玩家和AI的总资源价值差异
    const container = document.querySelector('.container');
    
    // 计算总资源价值
    let playerValue = 0;
    let aiValue = 0;
    
    for (const resourceId in gameState.playerResources) {
        const resourceType = Object.values(RESOURCE_TYPES).find(type => type.id === resourceId);
        if (resourceType) {
            playerValue += gameState.playerResources[resourceId] * resourceType.baseValue;
        }
    }
    
    for (const resourceId in gameState.aiResources) {
        const resourceType = Object.values(RESOURCE_TYPES).find(type => type.id === resourceId);
        if (resourceType) {
            aiValue += gameState.aiResources[resourceId] * resourceType.baseValue;
        }
    }
    
    // 移除之前的背景色类
    container.classList.remove('player-winning', 'ai-winning', 'tie-game');
    
    // 根据资源价值差异添加新的背景色类
    if (playerValue > aiValue) {
        container.classList.add('player-winning');
    } else if (aiValue > playerValue) {
        container.classList.add('ai-winning');
    } else {
        container.classList.add('tie-game');
    }
}

// 创建最终结果阶段
function createFinalResultPhase() {
    const finalResultPhase = document.createElement('div');
    finalResultPhase.id = 'finalResultPhase';
    finalResultPhase.className = 'phase';
    
    finalResultPhase.innerHTML = `
        <h2>游戏最终结果</h2>
        <div class="final-result">
            <p>总回合数：${gameState.maxRounds}</p>
            <p>你的最终收益：<span id="playerFinalTotal">${gameState.playerCoins}</span> 枚金币</p>
            <p>AI的最终收益：<span id="aiFinalTotal">${gameState.aiCoins}</span> 枚金币</p>
            <p>总创造财富：<span id="totalWealth">${gameState.playerCoins + gameState.aiCoins}</span> 枚金币</p>
        </div>
        <div class="action-buttons">
            <button id="viewHistory">查看历史记录</button>
            <button id="restartGameFinal">重新开始</button>
        </div>
    `;
    
    document.querySelector('.container').appendChild(finalResultPhase);
    elements.finalResultPhase = finalResultPhase;
    
    // 添加按钮事件（跳转到独立历史页）
    document.getElementById('viewHistory').addEventListener('click', () => {
        // 将本局会话历史通过URL hash传递，避免本地文件协议下的本地存储隔离问题
        try {
            const sessionEncoded = btoa(encodeURIComponent(JSON.stringify(gameState.history)));
            window.location.href = 'history.html#session=' + sessionEncoded;
        } catch (e) {
            window.location.href = 'history.html';
        }
    });
    document.getElementById('restartGameFinal').addEventListener('click', resetGame);
}

// 更新最终结果阶段
function updateFinalResultPhase() {
    document.getElementById('playerFinalTotal').textContent = gameState.playerCoins;
    document.getElementById('aiFinalTotal').textContent = gameState.aiCoins;
    document.getElementById('totalWealth').textContent = gameState.playerCoins + gameState.aiCoins;
}

// 创建历史记录阶段
function createHistoryPhase() {
    const historyPhase = document.createElement('div');
    historyPhase.id = 'historyPhase';
    historyPhase.className = 'phase';
    
    historyPhase.innerHTML = `
        <h2>游戏历史记录</h2>
        <div class="history-container">
            <table id="historyTable">
                <thead>
                    <tr>
                        <th>回合</th>
                        <th>投资</th>
                        <th>增值</th>
                        <th>返还</th>
                        <th>你的收益</th>
                        <th>AI收益</th>
                        <th>AI策略</th>
                    </tr>
                </thead>
                <tbody id="historyTableBody">
                </tbody>
            </table>
        </div>
        <div class="trust-chart">
            <h3>信任曲线</h3>
            <div id="trustChart" class="chart-container">
                <!-- 这里将来可以添加图表 -->
                <p>投资比例变化图表将在这里显示</p>
            </div>
        </div>
        <button id="backToFinal">返回结果</button>
    `;
    
    document.querySelector('.container').appendChild(historyPhase);
    elements.historyPhase = historyPhase;
    
    // 添加按钮事件
    document.getElementById('backToFinal').addEventListener('click', () => switchPhase('finalResult'));
}

// 更新历史记录阶段
function updateHistoryPhase() {
    const tableBody = document.getElementById('historyTableBody');
    tableBody.innerHTML = '';
    
    // 添加历史记录行
    gameState.history.forEach(record => {
        const row = document.createElement('tr');
        
        // 为心理战AI添加返还率信息
        let strategyDisplay = getStrategyName(record.strategy);
        if ((record.strategy === 'psychological' || record.strategy === 'vengeful') && record.returnRate) {
            strategyDisplay += ` (${Math.round(parseFloat(record.returnRate) * 100)}%)`;
        }
        
        row.innerHTML = `
            <td>${record.round}</td>
            <td>${record.investment}</td>
            <td>${record.multipliedAmount}</td>
            <td>${record.returnAmount}</td>
            <td>${record.playerGain > 0 ? '+' : ''}${record.playerGain}</td>
            <td>${record.aiGain > 0 ? '+' : ''}${record.aiGain}</td>
            <td>${strategyDisplay}</td>
        `;
        
        // 对欺骗行为进行标记
        if (record.strategy === 'psychological' && parseFloat(record.returnRate) <= 0.15) {
            row.classList.add('deception-round');
            row.title = '这一轮AI可能使用了欺骗策略';
        }
        
        tableBody.appendChild(row);
    });
    
    // 如果有足够的历史数据，创建投资-返还比例图表
    if (gameState.history.length >= 2) {
        createTrustChart();
    }
}

// 创建信任曲线图表
function createTrustChart() {
    const chartContainer = document.getElementById('trustChart');
    chartContainer.innerHTML = '';
    
    // 简单的文本表示图表
    // 在实际项目中，这里可以使用Chart.js等库创建真实图表
    let chartHTML = '<div class="text-chart">';
    
    // 投资比例变化
    chartHTML += '<div class="chart-row"><strong>投资比例变化：</strong> ';
    gameState.history.forEach((record, index) => {
        const investmentRatio = record.investment / 10;
        const barWidth = Math.round(investmentRatio * 100);
        chartHTML += `<span class="chart-bar" style="width:${barWidth}px;" title="回合${record.round}: ${record.investment}/10">${record.round}</span>`;
    });
    chartHTML += '</div>';
    
    // 返还比例变化
    chartHTML += '<div class="chart-row"><strong>返还比例变化：</strong> ';
    gameState.history.forEach((record, index) => {
        // 确保不会除以0
        const returnRatio = record.multipliedAmount > 0 ? record.returnAmount / record.multipliedAmount : 0;
        const barWidth = Math.max(5, Math.round(returnRatio * 100)); // 至少5像素宽以保证可见
        chartHTML += `<span class="chart-bar ai-bar" style="width:${barWidth}px;" title="回合${record.round}: ${Math.round(returnRatio*100)}%">${record.round}</span>`;
    });
    chartHTML += '</div>';
    
    chartHTML += '</div>';
    chartContainer.innerHTML = chartHTML;
}

// 获取策略名称
function getStrategyName(strategy) {
    const strategyNames = {
        'good': '好人AI',
        'bad': '坏人AI',
        'fair': '公平AI',
        'psychological': '心理战AI',
        'vengeful': '报复性AI'
    };
    return strategyNames[strategy] || strategy;
}

/**
 * 根据资源池配置初始化游戏资源
 * @param {Object} poolConfig 资源池配置
 * @returns {Object} 初始化的游戏状态
 */
function initializeGameState(poolConfig = POOL_CONFIGS.BASIC) {
    const playerResources = {};
    const aiResources = {};
    
    // 初始化所有资源类型
    Object.values(RESOURCE_TYPES).forEach(type => {
        playerResources[type.id] = poolConfig.initialResources[type.id] || 0;
        aiResources[type.id] = 0;
    });
    
    return {
        playerResources,
        aiResources,
        currentPhase: 'investment',
        investment: {},
        multipliedAmount: {},
        returnAmount: {},
        currentRound: 1,
        maxRounds: 5,
        poolConfig,
        history: []
    };
}

// 重置游戏
function resetGame() {
    // 获取当前选择的资源池配置
    let selectedPoolConfig = POOL_CONFIGS.BASIC;
    if (elements.poolSelector) {
        const selectedPoolName = elements.poolSelector.value;
        selectedPoolConfig = Object.values(POOL_CONFIGS).find(config => config.name === selectedPoolName) || POOL_CONFIGS.BASIC;
    }
    
    // 初始化游戏状态
    gameState = initializeGameState(selectedPoolConfig);

    // 重置投资滑块
    if (elements.investmentSlider) {
        const maxGold = gameState.playerResources[RESOURCE_TYPES.GOLD.id] || 10;
        elements.investmentSlider.max = maxGold;
        elements.investmentSlider.value = Math.min(5, maxGold);
        if (elements.investmentValue) {
            elements.investmentValue.textContent = elements.investmentSlider.value;
        }
    }
    
    // 重置信任值滑块（如果存在）
    if (elements.trustInvestmentSlider) {
        const maxTrust = gameState.playerResources[RESOURCE_TYPES.TRUST.id] || 0;
        elements.trustInvestmentSlider.max = maxTrust;
        elements.trustInvestmentSlider.value = 0;
        if (elements.trustInvestmentValue) {
            elements.trustInvestmentValue.textContent = '0';
        }
    }
    
    // 重置风险点滑块（如果存在）
    if (elements.riskInvestmentSlider) {
        const maxRisk = gameState.playerResources[RESOURCE_TYPES.RISK.id] || 0;
        elements.riskInvestmentSlider.max = maxRisk;
        elements.riskInvestmentSlider.value = 0;
        if (elements.riskInvestmentValue) {
            elements.riskInvestmentValue.textContent = '0';
        }
    }

    updateUI();
    
    // 清理容器背景状态类
    const container = document.querySelector('.container');
    if (container) {
        container.classList.remove('player-winning', 'ai-winning', 'tie-game');
    }

    switchPhase('investment');
}

/**
 * 更新资源显示
 * @param {HTMLElement} container 容器元素
 * @param {Object} resources 资源对象
 */
function updateResourceDisplay(container, resources) {
    if (!container) return;
    
    // 清空现有内容
    container.innerHTML = '';
    
    // 为每种资源创建显示元素
    for (const resourceId in resources) {
        if (resources[resourceId] > 0) {
            const resourceType = Object.values(RESOURCE_TYPES).find(type => type.id === resourceId);
            if (!resourceType) continue;
            
            const resourceElement = document.createElement('div');
            resourceElement.className = 'resource-item';
            resourceElement.innerHTML = `
                <span class="resource-icon" style="color: ${resourceType.color}">${resourceType.icon}</span>
                <span class="resource-amount">${resources[resourceId]}</span>
                <span class="resource-name">${resourceType.name}</span>
            `;
            container.appendChild(resourceElement);
        }
    }
    
    // 如果没有资源，显示一个默认值
    if (container.children.length === 0) {
        container.innerHTML = '<div class="resource-item">无资源</div>';
    }
}

// 更新UI显示
function updateUI() {
    // 兼容旧版UI
    if (elements.playerCoins) {
        elements.playerCoins.textContent = gameState.playerResources[RESOURCE_TYPES.GOLD.id] || 0;
    }
    if (elements.aiCoins) {
        elements.aiCoins.textContent = gameState.aiResources[RESOURCE_TYPES.GOLD.id] || 0;
    }
    
    // 更新新版资源显示
    if (elements.playerResourcesContainer) {
        updateResourceDisplay(elements.playerResourcesContainer, gameState.playerResources);
    }
    if (elements.aiResourcesContainer) {
        updateResourceDisplay(elements.aiResourcesContainer, gameState.aiResources);
    }
    
    // 更新资源池选择器
    if (elements.poolSelector) {
        elements.poolSelector.value = gameState.poolConfig.name;
    }
}

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', initGame);